package com.fjwt.gz.zhyx.sms;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.zhyx.AESUtils;
import com.fjwt.gz.zhyx.SignUtils;
import com.fjwt.gz.zhyx.ZhyxKit;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class TYYSmsService {


    public Boolean sendSmsCode(JSONObject jsonObject) {
        log.info("发送短信加密前请求参数:{}", JSONUtil.toJsonStr(jsonObject));
        String smsUrl = ZhyxKit.SMS_URL;
        String encryptStr = AESUtils.getInstance().encrypt(JSONUtil.toJsonStr(jsonObject));
        long timeStamp = System.currentTimeMillis();
        String authSign = SignUtils.getEncryptSign(encryptStr, timeStamp);

        log.info("发送短信请求地址：{}, 请求参数：{}, 加密串：{}", smsUrl, encryptStr, authSign);
        try {

            HttpResponse response = HttpRequest.post(smsUrl)
                    .header("Content-Type", MediaType.TEXT_PLAIN_VALUE)
                    .header("sign-type", SignUtils.SIGN_TYPE)
                    .header("auth-apikey", SignUtils.API_KEY)
                    .header("auth-sign", authSign)
                    .header("auth-timestamp", String.valueOf(timeStamp))
                    .header("Referer","https://jrstyy.post183.net")
                    .timeout(20000)
                    .body(encryptStr)
                    .execute();
            String body = response.body();
            log.info("发送短信返回的数据是：{}", JSONUtil.toJsonStr(body));
            JSONObject reapJson = JSONObject.parseObject(body);
            String code = reapJson.getString("code");
            if ("0".equals(code)) {
                String data = reapJson.getString("data");
                JSONObject dataJson = JSONObject.parseObject(data);
                String status = dataJson.getString("status");
                if ("0".equals(status)) {
                    return true;
                } else if ("1".equals(status)) {
                    throw new BizException("短信未发送，请稍后再试");
                } else if ("2".equals(status)) {
                    throw new BizException("短信发送失败，请稍后再试");
                }
            } else if ("9999".equals(code)) {
                throw new BizException(reapJson.getString("msg"));
            }else {
                throw new BizException("短信发送失败，请稍后再试");
            }

        } catch (Exception e) {
            log.info("发送短信异常：{}", e.getMessage());
            throw new BizException("发送短信异常：" + e.getMessage());
        }
        return false;

    }


}